//
//  TGWebViewController.m
//  TGWebViewController
//
//  Created by 赵群涛 on 2017/9/15.
//  Copyright © 2017年 QR. All rights reserved.
//

#import "TGWebViewController.h"
#import "TGWebProgressLayer.h"
#import <WebKit/WebKit.h>
#import <MobileCoreServices/MobileCoreServices.h>
#import "EDSignInDetailViewController.h"
#import "EDExchangeCenterViewController.h"
#import "TGWebViewController.h"
#import "EDTodayGamesVC.h"
#import "TwoBtnsView.h"
#import "EDRebateViewController.h"
#import "EDLuckCashViewController.h"
#import "EDBirthdayLuckViewController.h"
#import "EDHundredTimesVC.h"
#import "EDTournamentViewController.h"
#import "EDRecommendFriendsViewController.h"
#import "EDTigerFitViewController.h"
#import "EDWelfareCenterViewController.h"


@interface TGWebViewController ()
<WKUIDelegate,WKScriptMessageHandler,UIImagePickerControllerDelegate,UINavigationControllerDelegate,WKNavigationDelegate>
@property (nonatomic, strong)WKWebView *tgWebView;

@property (nonatomic, strong)TGWebProgressLayer *webProgressLayer;


@end

@implementation TGWebViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor = [UIColor whiteColor];
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.navigationItem.title = self.webTitle;
    [self setUpUI];
}

- (void)setUpUI {
    
    
    UIButton *backBtn = [UIButton buttonWithType:UIButtonTypeCustom];

    backBtn.frame = CGRectMake(0, 0, 14, 28);
    [backBtn setImage:[UIImage imageNamed:@"return"] forState:UIControlStateNormal];
    [backBtn addTarget:self action:@selector(backButton:) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:backBtn];
    
    WKWebViewConfiguration *configuration = [[WKWebViewConfiguration alloc] init];
    WKUserContentController *userContentController = [[WKUserContentController alloc] init];
  //  window.webkit.messageHandlers.Deposit.postMessage({id: "p1_19fsd", name: "存110送100", other: "存款等于:110"});
    [userContentController addScriptMessageHandler:self name:@"Deposit"];
       [userContentController addScriptMessageHandler:self name:@"DailySign"];
       [userContentController addScriptMessageHandler:self name:@"PersonalMatch"];
     [userContentController addScriptMessageHandler:self name:@"Welfare"];
       [userContentController addScriptMessageHandler:self name:@"friendRecommend"];
       [userContentController addScriptMessageHandler:self name:@"DailyGame"];
       [userContentController addScriptMessageHandler:self name:@"TeamMatch"];
       [userContentController addScriptMessageHandler:self name:@"Qbb"];
       [userContentController addScriptMessageHandler:self name:@"Dep"];
    configuration.userContentController = userContentController;
    self.tgWebView = [[WKWebView alloc] initWithFrame:self.view.bounds configuration:configuration] ;
    self.tgWebView.navigationDelegate =self;
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:self.url]];
    [self.tgWebView loadRequest:request];
    [self.view addSubview:self.tgWebView];
    
    
    self.webProgressLayer = [[TGWebProgressLayer alloc] init];
    self.webProgressLayer.frame = CGRectMake(0, 42, WIDTH, 2);
    self.webProgressLayer.strokeColor =EDColor_BaseBlue.CGColor;
    [self.navigationController.navigationBar.layer addSublayer:self.webProgressLayer];
    
    
}

- (void)backButton:(UIButton *)btn {
    [self.navigationController popViewControllerAnimated:YES];
    [self.webProgressLayer removeFromSuperlayer];
}

#pragma mark - UIWebViewDelegate
- (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation {
    [self.webProgressLayer tg_startLoad];
}

- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation {
    [self.webProgressLayer tg_finishedLoadWithError:nil];
}

- (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(WKNavigation *)navigation withError:(NSError *)error {
    [self.webProgressLayer tg_finishedLoadWithError:error];
    
}
#pragma mark -- WKScriptMessageHandler
/**
 *  JS 调用 OC 时 webview 会调用此方法
 *
 *  @param userContentController  webview中配置的userContentController 信息
 *  @param message                JS执行传递的消息
 */

- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message
{
    //JS调用OC方法
    
    //message.boby就是JS里传过来的参数
    NSLog(@"body:%@",message.body);
    
    if ([message.name isEqualToString:@"Deposit"]) {
        [self depositWithInformation:message.body];
        
    }else if ([message.name isEqualToString:@"DailySign"]){
        //
        EDSignInDetailViewController * signVC = [EDSignInDetailViewController new];
        signVC.title = @"每日签到";
        [self.navigationController pushViewController:signVC animated:YES];
        
    }
    else if ([message.name isEqualToString:@"PersonalMatch"]){
        EDTournamentViewController * exchangeVC = [EDTournamentViewController new];
        exchangeVC.title = @"个人锦标赛";
        [self.navigationController pushViewController:exchangeVC animated:YES];
    }
    else if ([message.name isEqualToString:@"friendRecommend"]){
        EDRecommendFriendsViewController * recomdVC = [EDRecommendFriendsViewController new];
        recomdVC.title =@"推荐好友";
        [self.navigationController pushViewController:recomdVC animated:YES];
    }
    else if ([message.name isEqualToString:@"DailyGame"]){
        EDTodayGamesVC * gameVC = [EDTodayGamesVC new];
        gameVC.title = @"今日特色游戏";
        [self.navigationController pushViewController:gameVC animated:YES];
        
    }else if ([message.name isEqualToString:@"TeamMatch"]){
        EDTigerFitViewController * tigerVC = [EDTigerFitViewController new];
        tigerVC.title = @"组队打虎";
        [self.navigationController pushViewController:tigerVC animated:YES];
    }else if ([message.name isEqualToString:@"Qbb"]){
        EDHundredTimesVC * gameVC = [EDHundredTimesVC new];
        gameVC.title = @"千倍百倍（PT、PS平台）";
        [self.navigationController pushViewController:gameVC animated:YES];
        
    }else if ([message.name isEqualToString:@"Welfare"]){
       EDWelfareCenterViewController * welfareVC = [EDWelfareCenterViewController new];
        welfareVC.title = @"福利领取区";
        [self.navigationController pushViewController:welfareVC animated:YES];
        
    }
    else if ([message.name isEqualToString:@"Dep"]){
        [AppDelegate shareAppdelegate].index = 0;
         [AppDelegate shareAppdelegate].loveHuodongID = @"";
        [[NSNotificationCenter defaultCenter]postNotificationName:@"loveHuodongAction" object:nil userInfo:[NSDictionary dictionary]];
        self.navigationController.tabBarController.selectedIndex = 1;
        [self.navigationController popToRootViewControllerAnimated:YES];
        
    }
    
}
#pragma mark - Method
- (void)depositWithInformation:(NSDictionary *)dic
{
    if (![dic isKindOfClass:[NSDictionary class]]) {
        return;
    }
    
    dispatch_async(dispatch_get_main_queue(), ^{
        [AppDelegate shareAppdelegate].index = 0;
        NSMutableDictionary * infoDicc = [NSMutableDictionary dictionary];
        [infoDicc setValue:[dic jsonString:@"id"] forKey:@"loveId"];
         [AppDelegate shareAppdelegate].loveHuodongID = [dic jsonString:@"id"];
        [[NSNotificationCenter defaultCenter]postNotificationName:@"loveHuodongAction" object:nil userInfo:infoDicc];
        self.navigationController.tabBarController.selectedIndex = 1;
        [self.navigationController popToRootViewControllerAnimated:YES];
    });
    
    
}
- (void)dealloc {
    [self.webProgressLayer tg_closeTimer];
     [self.tgWebView.configuration.userContentController removeScriptMessageHandlerForName:@"Deposit"];
         [self.tgWebView.configuration.userContentController removeScriptMessageHandlerForName:@"DailySign"];
         [self.tgWebView.configuration.userContentController removeScriptMessageHandlerForName:@"PersonalMatch"];
         [self.tgWebView.configuration.userContentController removeScriptMessageHandlerForName:@"friendRecommend"];
         [self.tgWebView.configuration.userContentController removeScriptMessageHandlerForName:@"DailyGame"];
         [self.tgWebView.configuration.userContentController removeScriptMessageHandlerForName:@"TeamMatch"];
         [self.tgWebView.configuration.userContentController removeScriptMessageHandlerForName:@"Qbb"];
         [self.tgWebView.configuration.userContentController removeScriptMessageHandlerForName:@"Dep"];
         [self.tgWebView.configuration.userContentController removeScriptMessageHandlerForName:@"Welfare"];
    [_webProgressLayer removeFromSuperlayer];
    _webProgressLayer = nil;
}




@end
